﻿using Candy.Model;
using GalaSoft.MvvmLight.Threading;
using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace Candy.Infrastructure
{
    public static class ErrorHandler
    {

        static ErrorWindow _errorWindow = new ErrorWindow();

        public static void Handle(Exception ex)
        {
            DispatcherHelper.CheckBeginInvokeOnUI(() =>
             {
                 _errorWindow.Exception = ex;
                 _errorWindow.Show();
             });
        }

        public static void HandleBusinessError(Exception ex, string title)
        {
            if (_errorElement == null)
                throw new InvalidOperationException("Errorhandler is not initialized yet.");
            DispatcherHelper.CheckBeginInvokeOnUI(() =>
             {
                 _errorElement.Show(ex, title);
             });
        }

        public static void Reset()
        {
            if (_errorElement == null)
                throw new InvalidOperationException("Errorhandler is not initialized yet.");
            DispatcherHelper.CheckBeginInvokeOnUI(() =>
                {
                    _errorElement.Close();
                });
        }

        static IErrorInfoControl _errorElement;
        public static void Initialize(IErrorInfoControl errorElement)
        {
            if (errorElement != null)
                _errorElement = errorElement;
            else
                throw new ArgumentNullException("ErrorInfoControl can't be null.");
        }



        public static void HandleDomainError(System.ServiceModel.DomainServices.Client.OperationBase op, string title)
        {
            if (_errorElement == null)
                throw new InvalidOperationException("Errorhandler is not initialized yet.");

            if (op.HasError)
            {
                op.MarkErrorAsHandled();
                DispatcherHelper.CheckBeginInvokeOnUI(() =>
             {
                 _errorElement.Show(op.Error, title);
             });
            }
        }


        public static void HandleDomainError(CandyOperationBase op, string title)
        {
            if (_errorElement == null)
                throw new InvalidOperationException("Errorhandler is not initialized yet.");

            if (op.HasError)
            {
                op.MarkErrorAsHandled();
                DispatcherHelper.CheckBeginInvokeOnUI(() =>
             {
                 _errorElement.Show(op.Error, title);
             });
            }
        }
    }
}
